<template>
	<view class="left clearfix bai" style="height:100%;">
		<children-top :title="chapterData.title" :page="'/pages/audio/chapter?id='+id"></children-top>
		
		<view class="tim-content left clearfix">
			<view class="tim-left left clearfix">
				<view class="tim-left-title left clearfix">
					输入配音文案
				</view>
				
				<create-textarea :chapter="chapterData" :fontTotalNumber="1600" :defaultContent="content" @change="getContent"></create-textarea>
			</view>
			<view class="tim-right right clearfix relative">
				<view class="tim-right-title left clearfix relative">
					音色配置
					
					<view class="tim-use-box left clearfix absolute">
						<image :src="currentTimbre.avatar" style="width:100%;height:100%;border-radius: 50%;"></image>
					</view>
				</view>
				<view class="tim-right-yinse left clearfix">
					
					
					<view :style="currentTimbre._id == item._id?'border:.1px solid #8cde9b;background-color:#d1f2d7;':'border:.1px solid #eee;background-color:#fff;'" class="tim-right-item left clearfix" v-for="(item,index) in timbre" @click="setSelectTimbre(item,index)">
						<view class="tim-right-image left clearfix relative">
							<image :src="item.avatar" style="width:100%;height:100%;border-radius: 50%;"></image>
							<view class="tim-right-play absolute">
								<uni-icons v-if="currentPlayAudioIndex!=index || currentPlayAudioStatus=='pause' || currentPlayAudioIndex===null" type="icon-bofang2" size="18" @click="setPlay(item,'play',index)" color="#fff" custom-prefix="iconfont"></uni-icons>
								<uni-icons v-if="currentPlayAudioIndex==index && currentPlayAudioStatus=='play'" type="icon-weibiaoti519" size="18" @click="setPlay(item,'pause',index)" color="#fff" custom-prefix="iconfont"></uni-icons>
							</view>
						</view>
						<view class="tim-right-text left ellipsis">
							{{item.name}}
						</view>
					</view>
					
					
				</view>
				
				<view class="tim-right-title left clearfix" style="margin-top:10px;">
					属性配置
				</view>
				
				<view class="tim-right-shuxing left clearfix" style="margin-top:10px;">
					
					<view class="tim-right-shuxing-item left clearfix">
						<view>
							音量
						</view>
						<view>
							<slider :value="volume" :max="100" :min="20" block-size="18" :show-value="true" @change="sliderChange('volume')" step="1" />
						</view>
					</view>
					
					<view class="tim-right-shuxing-item left clearfix">
						<view>
							语速
						</view>
						<view>
							<slider :value="rate" :max="2" :min="0.5" block-size="18" :show-value="true" @change="sliderChange('rate')" step="0.1" />
						</view>
					</view>
					
					<view class="tim-right-shuxing-item left clearfix">
						<view>
							语调
						</view>
						<view>
							<slider :value="pitch" :max="2" :min="0.5" block-size="16" :show-value="true" @change="sliderChange('pitch')" step="0.1" />
						</view>
					</view>
					
					
				</view>
				
				<view class="tim-submit left clearfix absolute" @click="createAudio">
					一键生成
				</view>
				
			</view>
		</view>
	</view>
</template>
<style>
	body,uni-page-body{height:100%;}
	uni-slider .uni-slider-handle-wrapper{position: relative;
    height: 4px;
    border-radius: 5px;
    background-color: #e9e9e9;
    cursor: pointer;
    transition: background-color 0.3s ease;
    -webkit-tap-highlight-color: transparent}
</style>
<style scoped>
	.tim-use-box{width:45px;height:45px;border-radius: 50%;border:1px solid #eee;right:20px;top:-13px;}
	.tim-right-play{width:25px;line-height:25px;text-align:center;height:25px;background:rgba(100,100,100, .3);left:10px;top:10px;border-radius: 50%;z-index:100; }
	.tim-right-text{width:100%;line-height:15px;text-align: center;color:#666;font-size:13px;}
	.tim-right-image{width:45px;height:45px;margin:12.5px;border:1px solid #eee;border-radius: 50%;margin-top:5px;margin-bottom:10px;}
	.tim-right-item{width:70px;height:85px;background:#fff;border-radius: 5px;margin:10px;cursor:pointer;border:1px solid #eee;margin-left:9px;margin-right:4px;}
	.tim-submit{width:80%;margin-left:10%;line-height:40px;background-image: linear-gradient(90deg, #4287fe, #298bfe 25%, #0f8ffd 51%, #25b4c1);color:#fff;text-align: center;border-radius: 10px;bottom:30px;left:0;right:0;cursor:pointer;}
	.tim-right-shuxing-item view:last-child{width:calc(100% - 80px);margin-left:20px;line-height:30px;height:30px;margin-top:-10px;}
	.tim-right-shuxing-item view:first-child{width:60px;text-align: center;line-height:30px;font-size:14px;}
	.tim-right-shuxing-item view{float:left;}
	.tim-right-shuxing-item{width:100%;height:30px;line-height:30px;margin-top:20px;}
	.tim-right-shuxing{width:calc(100% - 40px);margin-left:20px;margin-right:20px;margin-top:20px;}
	.tim-right-yinse{width:calc(100% - 40px);margin:20px;height:40%;border:1px solid #f8f8f8;overflow:auto;background-image: url('/static/images/body-bj.png');background-color: rgb(247, 247, 249);border-radius: 5px;}
	.tim-right-title{width:calc(100% - 20px);padding-left:20px;margin-top:20px;font-size:14px;}
	.tim-left-title{width:calc(100% - 20px);padding-left:20px;lcolor: rgb(21, 27, 38);font-size: 18px;font-weight: 500;line-height: 28px;margin-top:20px;}
	.tim-right{width:28%;height:100%;background:#fff;border-radius: 15px;}
	.tim-left{width:70%;height:100%;background:#fff;border-radius: 15px;}
	.tim-content{width:96%;height:calc(100% - 110px);margin-left:2%;margin-top:70px;}
</style>

<script>
	var db = uniCloud.database();
	var aliyun = uniCloud.importObject('aliyun',{customUI:true});
	export default {
		data() {
			return {
				pitch:1,//语调
				volume:100,//音量
				rate:1,//语速
				timbre:[],
				innerAudioContext:null,//音频播放数据
				audioItem:{},//正在播放的数据
				currentPlayAudioIndex:null,//当前正在播放的index
				currentPlayAudioStatus:null,//当前播放状态
				chapterId:'',
				userinfo:{},//登录用户信息
				chapterData:{},
				currentTimbre:{},//当前使用的音色
				content:'',
				id:''
			}
		},
		created() {
			var that = this;
			that.getTimbre();
			uni.getStorage({
				key:'login-userinfo',
				success:function(res){
					var userinfo = res.data;
					if(userinfo && userinfo._id){
						that.userinfo = userinfo;
					}else{
						uni.navigateTo({
							url: '/pages/index/index'
						});
					}
				},
				fail() {
					uni.navigateTo({
						url: '/pages/index/index'
					});
				}
			});
			
			uni.getStorage({
				key:'current-timbre',
				success:function(res){
					if(res && res.data){
						that.currentTimbre = res.data;
					}else{
						that.currentTimbre = this.timbre[0];
					}
				},
				fail() {
					that.currentTimbre = this.timbre[0];
				}
			})
		},
		onLoad(e) {
			if(e && e.chapter){
				this.chapterId = e.chapter;
				this.id = e.id;
				//查询出默认章节信息
				this.getChapterById(e.chapter);
			}
		},
		methods: {
			//生成音频文件
			createAudio(){
					var that = this;
					var content = this.content;
					var timbre = this.currentTimbre;
					var length = content.length;
					var id = this.chapterId;
					if(!id){
						uni.showToast({
							title:'缺少id参数，配音无法执行',
							icon:'error',
							duration:2000
						})
						
						return false;
					}
					
					if(!content){
						uni.showToast({
							title:'请输入文本内容',
							icon:'error',
							duration:2000
						})
						
						return false;
					}
					
					if(length > 1600){
						uni.showToast({
							title:'当前字数为'+length+',超出了1600字',
							icon:'none',
							duration:2000
						})
						
						return false;
					}
					uni.showLoading({
						title:'合成中，约2分钟'
					})
					var fileName = that.generateUUID();
					var data = {
						text:content,//合成文本
						voice:timbre.voice,//音色
						volume:that.volume,//音量
						rate:that.rate,//语速
						pitch:that.pitch,//语调,
						fileName:fileName
					}
					
					// 创建一个新的Date对象
					const today = new Date();
					// 获取年、月、日
					const year = today.getFullYear();
					const month = (today.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始的，所以需要+1
					const day = today.getDate().toString().padStart(2, '0');
					// 使用模板字符串组合日期
					const formattedDate = `${year}${month}${day}`;
					var filePath = 'http://ai.mofang360.com/public/'+formattedDate+'/'+fileName+'.mp3';
					//入库数据
					var updateData = {
						audio:filePath,
						content:that.content,
						create_date:new Date().getTime()
					}
						//更新到数据库
						db.collection('timbre_title').where({_id:this.chapterId}).update(updateData).then(addRes=>{
							//异步发送给接口
							aliyun.getCosyVoiceFromPhp(data).then(aRes=>{
								console.log('配音结果',aRes);
							}).catch(aErr=>{
								console.log('配音失败',aErr);
							});
							uni.showToast({
								title:'合成成功',
								icon:'error',
								duration:2000
							})
							setTimeout(function(){
								uni.redirectTo({
									url:  '/pages/audio/chapter?id='+that.id
								});
							},2000);
						}).catch(err=>{
							console.log('出错了',err);
						});
			},
			//uuid
			generateUUID() {
			    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			        var r = Math.random() * 16 | 0,
			            v = c === 'x' ? r : (r & 0x3 | 0x8);
			        return v.toString(16);
			    });
			},
			//获取内容
			getContent(text){
				this.content = text;
			},
			//点击使用音色以后
			setSelectTimbre(item,index){
				var that = this;
				//把当前使用的音色缓存起来，以便以后继续使用
				uni.setStorage({
					key:'current-timbre',
					data:item,
					success() {
						that.currentTimbre = item;
					}
				})
			},
			//查询出默认章节信息
			getChapterById(id){
				if(id){
					db.collection('timbre_title').where({_id:id}).get({getOne:true}).then(res=>{
						var data = res.result.data;
						this.chapterData = data;
						this.content = data.content;
					});
				}
				
			},
			//设置播放音频
			setPlay(item,act,index){
				var that = this;
				if(item.audio_url != this.audioItem.audio_url){
					if(that.innerAudioContext){
						that.innerAudioContext.stop();
					}
					var innerAudioContext = uni.createInnerAudioContext();
					this.innerAudioContext = innerAudioContext;
					this.audioItem = item;
					innerAudioContext.src = item.audio_url;
					innerAudioContext.autoplay = true;
				}else{
					var innerAudioContext = this.innerAudioContext;
				}
				
				if(act == 'play'){
					innerAudioContext.play();
					innerAudioContext.onPlay(()=>{
						that.currentPlayAudioIndex = index;
						that.currentPlayAudioStatus = 'play';
					});
				}else if(act == 'pause'){
					innerAudioContext.pause();
					that.currentPlayAudioStatus = 'pause';
				}
				
				innerAudioContext.onEnded(()=>{
					that.currentPlayAudioStatus = 'pause';
				});
			},
			//查询出音色
			getTimbre(){
				db.collection('timbre').where({type:'cosyvoice'}).orderBy('_id desc').get().then(res=>{
					var data = res.result.data;
					this.timbre = data;
				});
			}
		}
	}
</script>

